package com.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.common.Result;
import com.blog.dto.LoginDto;
import com.blog.dto.RegisterDto;
import com.blog.pojo.User;
import com.blog.service.SendMailService;
import com.blog.service.UserService;
import com.blog.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * 用户相关
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SendMailService sendMailService;

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest request;

    //临时存储验证码，使用过后会及时删除内容
    private HashMap<String, String> hashMap = new HashMap<>();

    /**
     * 发送验证码
     *
     * @param userAccount 用户账号
     * @return Result<String>
     */
    @GetMapping("/sendEmail")
    public Result<String> sendCode(@RequestParam String userAccount) {
        return Result.success(userService.sendUserCode(userAccount, hashMap));
    }

    /**
     * 用户注册
     *
     * @param registerDto 注册传输对象dto
     * @return Result<String>
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterDto registerDto) {
        String userAccount = registerDto.getUserAccount();
        String code = hashMap.get(userAccount);
        if (!"".equals(userAccount) && userAccount != null) {
            if (!registerDto.getCode().equals(code)) {
                //如果输入的验证码和session中的不同
                return Result.error("验证码错误！");
            }
            //验证码校验正确
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getUserAccount, userAccount);
            if (userService.getOne(userLambdaQueryWrapper) != null) {
                //如果用于已注册
                return Result.error("该用户已注册");
            }
            //还未注册
            User user = new User();
            //属性拷贝
            BeanUtils.copyProperties(registerDto, user);
            userService.save(user);
            hashMap.remove(userAccount);
            return Result.success("注册成功！");
        }
        return Result.error("请输入邮箱！");
    }

    /**
     * 用户登录
     *
     * @param user 用户对象
     * @return Result<LoginDto>
     */
    @PostMapping("/login")
    private Result<LoginDto> login(@RequestBody User user) {
        String userAccount = user.getUserAccount();
        if (!"".equals(userAccount) && userAccount != null) {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getUserAccount, user.getUserAccount());
            User u = userService.getOne(userLambdaQueryWrapper);
            if (u != null) {//用户存在
                if (u.getUserPassword().equals(user.getUserPassword())) {//密码正确
                    //生成token
                    String token = JwtUtil.createToken(u);
                    LoginDto loginDto = new LoginDto();
                    loginDto.setToken(token);
                    loginDto.setUserId(u.getId());
                    loginDto.setUserAccount(u.getUserAccount());
                    loginDto.setUsername(u.getUsername());
                    return Result.success(loginDto);
                } else {//密码错误
                    return Result.error("用户密码错误！");
                }
            } else {
                return Result.error("该用户不存在！");
            }
        } else {
            return Result.error("用户账号不能为空！");
        }
    }

    /**
     * 修改密码
     *
     * @param userAccount  用户账号
     * @param userPassWord 用户密码
     * @return Result<String>
     */
    @GetMapping("/changePassword")
    private Result<String> changePassword(String userAccount, String userPassWord, String code) {
        if (userAccount != null) {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getUserAccount, userAccount);
            User userServiceOne = userService.getOne(userLambdaQueryWrapper);
            if (userServiceOne != null) {
                //发送验证码
                userService.sendUserCode(userAccount, hashMap);
                //获取map中的验证码
                String codeInHashMap = hashMap.get(userAccount);
                if (code.equals(codeInHashMap)) {//验证码正确
                    //更新密码
                    userServiceOne.setUserPassword(userPassWord);
                    userService.updateById(userServiceOne);
                    return Result.success("密码修改成功！");
                }
                return Result.error("验证码错误");
            }
            return Result.error("该用户不存在！");
        } else if (code != null && !"".equals(code))
            return Result.error("请输入验证码！");
        return Result.error("请输入邮箱（账户名）！");
    }

    /**
     * 新增用户
     *
     * @param user 用户对象
     * @return Result<String>
     */
    @PostMapping("/save")
    private Result<String> save(@RequestBody User user) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId, user.getId());
        User userServiceOne = userService.getOne(userLambdaQueryWrapper);
        if (userServiceOne == null) {
            userService.save(user);
            return Result.success("增添成功！");
        }
        return Result.error("该用户已存在！请勿重复添加");
    }

    /**
     * 用户信息条件分页查询
     *
     * @param page     当前页
     * @param pageSize 页面大小
     * @param username 用户昵称
     * @param gender   用户性别
     * @return Result<Page>
     */
    @GetMapping("/page")
    private Result<Page> page(Integer page, int pageSize, String username, String gender) {
        //log.error("{}",request.getAttribute("adminAccount"));
        if (request.getAttribute("adminAccount") != null) {
            //管理员
            return Result.success(userService.page(page, pageSize, username, gender));
        }
        return Result.error("您没有此权限");
    }

    /**
     * 全部用户信息
     *
     * @return Result<List < User>>
     */
    @GetMapping("/list")
    private Result<List<User>> list() {
        if (request.getAttribute("adminAccount") != null) {
            return Result.success(userService.list());
        }
        return Result.error("您没有此权限");
    }

    /**
     * 删除单个用户信息
     *
     * @param userId 用户id
     * @return Result<String>
     */
    @DeleteMapping("/delete")
    private Result<String> delete(Long userId) {
        if (request.getAttribute("adminAccount") != null) {
            boolean flag = userService.deleteUser(userId);
            if (flag)
                return Result.success("删除成功！");
            else
                return Result.error("危险操作！请先删除该用户下的所有博客再进行此操作！");
        }
        return Result.error("您没有此权限");
    }

    /**
     * 修改用户信息
     *
     * @param user 用户对象
     * @return Result<String>
     */
    @PostMapping("/update")
    private Result<String> update(@RequestBody User user) {
        if (request.getAttribute("adminAccount") != null) {
            boolean flag = userService.updateById(user);
            if (flag)
                return Result.success("修改成功！");
            else
                return Result.error("修改失败！");
        }
        return Result.error("您没有此权限");
    }

    /**
     * 头像修改
     *
     * @param id        用户id
     * @param avatarUrl 头像url
     * @return Result<String>
     */
    @GetMapping("/avatarUpdate")
    private Result<String> avatarUpdate(Long id, String avatarUrl) {
        if (!"".equals(avatarUrl) && avatarUrl != null) {
            User user = new User();
            user.setId(id);
            user.setAvatarUrl(avatarUrl);
            userService.updateById(user);
            return Result.success("头像修改成功！");
        }
        return Result.error("请输入头像！");
    }

    /**
     * 禁用账户：禁用后不可登录博客系统。
     *
     * @param userId 用户id
     * @return Result<String>
     */
    @GetMapping("/changeStatue")
    private Result<String> changeStatue(@RequestParam Long userId) {
        if (request.getAttribute("adminAccount") != null) {
            User userServiceById = userService.getById(userId);
            Integer userStatus = userServiceById.getUserStatus();
            if (userStatus == 0) {//为启用状态
                //1为禁用状态
                userServiceById.setUserStatus(1);
                userService.updateById(userServiceById);
                return Result.success("该用户账号已被封禁！");
            }
            userServiceById.setUserStatus(0);
            userService.updateById(userServiceById);
            return Result.success("该用户账号已解封！");
        }
        return Result.error("您没有此权限");
    }

    /**
     * 用户详情信息
     *
     * @param userId 用户id
     * @return Result<User>
     */
    @GetMapping("/getUserInformation")
    private Result<User> getUserInformation(Long userId) {
        User userServiceById = userService.getById(userId);
        return Result.success(userServiceById);
    }
}
